/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package digitaldreamers.games.ddmonsters.servers.gameserver.network;

import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.AbPacketHandler;
import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.IConnectionHandler;
import digitaldreamers.libraries.games.servers.networkmanagement.packets.receiving.AbReceivablePacket;
import digitaldreamers.games.ddmonsters.servers.gameserver.components.PlayerComponent;
import digitaldreamers.games.ddmonsters.servers.gameserver.configurations.Configuration;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

/**
 *
 * @author DaoLe
 */
public class PacketHandler extends AbPacketHandler {
    public PacketHandler() {
        super();
    }
    
    public PacketHandler(IConnectionHandler pConnectionHandler) {
        super(pConnectionHandler);
    }
    
    @Override
    protected void handlePacket(byte[] pData) throws Exception {
        ByteArrayInputStream BAIS = new ByteArrayInputStream(pData);
        DataInputStream DIS = new DataInputStream(BAIS);
        try {
            // Get ID of the packet.
            int packetId = DIS.readInt();
            
            // Get the full qualified name of the packet class.
            PlayerComponent player = (PlayerComponent)mConnectionHandler.getPlayer();
            String packetClassName = Configuration.getInstance().getPacketClassName(packetId, player.getState(), player.getInRoomSubstate());
            String fullQualifiedPacketClassName = Configuration.RECEIVING_PACKET + packetClassName;
            
            // Create the packet.
            AbReceivablePacket receivedPacket = (AbReceivablePacket)Class.forName(fullQualifiedPacketClassName).getConstructor(IConnectionHandler.class).newInstance(mConnectionHandler);
        
            if(receivedPacket != null) {
                receivedPacket.fromByteArray(pData);
                receivedPacket.execute();
            }
        }
        catch(Exception ex) {
            throw ex;
        }
        finally {
            DIS.close();
        }
    }    
}
